﻿using AbpVnext_Module.Dto;
using AbpVnext_Module.Iservice;
using AbpVnext_Module.Model;
using AbpVnext_Module.Repository;
using AbpVnext_Order_Contracts.Dto;
using AbpVnext_Order_Contracts.Iservice;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System.Collections.Generic;
using System.Linq;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using Volo.Abp.Uow;

namespace AbpVnext_Module.Service
{
    /// <summary>
    /// 使用Abp领域服务模块Service
    /// </summary>
    [Dependency(ServiceLifetime.Transient)]
    //过滤Api自动控制器
    [RemoteService(IsEnabled = true)]   //true 显示 ，false不显示
    //[LogEnable]  //动态代理 拦截器(aop)
    //[Authorize("Product_Select")]   //Service授权
    public class ProductImageService : CrudAppService<ProductImage, //模型
                                                       ProductImageDto,  //结果出餐
                                                       int, //主键
                                                       ProductImagePageDto,//查询入参
                                                       ProductImageCreateDto,     //创建入参dto
                                                       ProductImageUpdateDto      //更新入参dto
                                                       >, IProductImageService
    {
        /// <summary>
        /// 属性医药
        /// </summary>
        public IProductImageRepository productImageRepository { get; set; }

        public IOrderService orderService { get; set; }

        public ILoggerFactory loggerFactory { get; set; }

        /// <summary>
        /// 属性注入
        /// </summary>
        //public IOrderRepository orderRepository { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="repository"></param>
        public ProductImageService(IProductImageRepository repository) : base(repository)
        {

        }

        public IObjectMapper _ObjectMapper { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authorize("Product_Select_Page")]
        public override async Task<PagedResultDto<ProductImageDto>> GetListAsync(ProductImagePageDto input)
        {
            var xxw = (await productImageRepository.GetDbContextAsync()).GetHashCode();
            var xxxw = (await productImageRepository.GetDbContextAsync()).GetHashCode();
            #region
            {
                // Repository.WhereIf()
                IQueryable<ProductImage> products = await Repository.GetQueryableAsync();
                List<ProductImage> productImages1 = products.Where(x => x.Url.Contains(input.Url)).Skip(0).Take(2).OrderBy(x => x.Id).ToList();
                var x = products.Where(x => x.Url.Contains(input.Url)).Count();

                DbSet<ProductImage> productImages = await Repository.GetDbSetAsync<ProductImage>();
                var data = productImages.Where(x => x.Url.Contains("1")).Skip(0).Take(2).OrderBy(x => x.Id).ToList();
                var xx = productImages.Where(x => x.Url.Contains("1")).Count();
            }
            #endregion

            #region 默认分页查询
            {
                //return base.GetListAsync(input);
                long count = await Repository.GetCountAsync();
                List<ProductImage> productImages = await productImageRepository.GetPagedListAsync(input);
                List<ProductImageDto> productImageDtos = ObjectMapper.Map<List<ProductImage>, List<ProductImageDto>>(productImages);
                PagedResultDto<ProductImageDto> pagedResultDto = new PagedResultDto<ProductImageDto>();
                pagedResultDto.TotalCount = count;
                pagedResultDto.Items = productImageDtos;
                return pagedResultDto;
            }
            #endregion
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //[Authorize("Product_Select")]
        public override async Task<ProductImageDto> GetAsync(int id)
        {
            //return base.GetAsync(id);
            ProductImage productImage = await Repository.GetAsync(id);
            ProductImageDto productImageDto = ObjectMapper.Map<ProductImage, ProductImageDto>(productImage);
            return productImageDto;
        }

        /// <summary>
        /// 自定义方法
        /// </summary>
        public void CustomeLog()
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [LogEnable]   //动态代理 拦截器(aop)
        //[AllowAnonymous]   //域名匿名访问,过滤鉴权拦截
        //[UnitOfWork]
        [Authorize("Product_Insert")]
        public override async Task<ProductImageDto> CreateAsync(ProductImageCreateDto input)
        {
            //作用域模式 用的同一个DbContext上下文
            //var xxw = (await productImageRepository.GetDbContextAsync()).GetHashCode();
            //var xxxw = (await productImageRepository.GetDbContextAsync()).GetHashCode()

            #region 动态代理（拦截器），不拦截自定义方法
            {
                CustomeLog();
            }
            #endregion

            #region  添加订单
            {
                //OrderCreateDto orderCreateDto = new OrderCreateDto() { OrderSn = "cesium2123", TotalPrice = "cesium2123" };
                //OrderDto dto = await orderService.CreateAsync(orderCreateDto);

                //动态代理
                ProductImageDto productImageDto = new ProductImageDto();
                //try
                //{
                ProductImage productImage = ObjectMapper.Map<ProductImageCreateDto, ProductImage>(input);
                ProductImage productImage1 = await Repository.InsertAsync(productImage);
                productImageDto = ObjectMapper.Map<ProductImage, ProductImageDto>(productImage1);
                return productImageDto;


                //动态代理会拦截框架内的增删改查方法
                //ProductImageDto productImageDto = new ProductImageDto();
                //var productImage1 = await base.CreateAsync(input);
                //return productImageDto;
            }
            #endregion

            #region 无特性事务 手动保存
            {
                //using (var uow = UnitOfWorkManager.Begin())
                //{
                //    ProductImageDto productImageDto = new ProductImageDto();
                //    try
                //    {
                //        productImageDto = new ProductImageDto();
                //        //try
                //        //{
                //        ProductImage productImage = ObjectMapper.Map<ProductImageCreateDto, ProductImage>(input);
                //        ProductImage productImage1 = await Repository.InsertAsync(productImage);
                //        productImageDto = ObjectMapper.Map<ProductImage, ProductImageDto>(productImage1);
                //        //
                //        //Order order = new Order();
                //        //order.OrderSn = "你好啊,8000";
                //        //order.TotalPrice = "8000";
                //        //await orderRepository.InsertAsync(order);

                //        //异常被捕获之后。
                //        //throw new Exception("出现错误了");

                //        //执行任务【工作单元】 提交任务 
                //        await uow.CompleteAsync();

                //    }
                //    catch (Exception ex)
                //    {
                //        await uow.RollbackAsync();
                //    }

                //    return productImageDto;
                //}
            }
            #endregion

            #region 有特性事务 手动保存
            {
                //ProductImageDto productImageDto = new ProductImageDto();
                ////try
                ////{
                //ProductImage productImage = ObjectMapper.Map<ProductImageCreateDto, ProductImage>(input);
                //ProductImage productImage1 = await Repository.InsertAsync(productImage);
                //productImageDto = ObjectMapper.Map<ProductImage, ProductImageDto>(productImage1);
                ////
                //Order order = new Order();
                //order.OrderSn = "你好啊,8000";
                //order.TotalPrice = "8000";
                ////添加数据
                ////框架自动实现了事务
                //await orderRepository.InsertAsync(order);

                ////异常被捕获之后，框架事务会失效。
                ////throw new Exception("出现错误了");

                ////手动保存
                //await CurrentUnitOfWork.SaveChangesAsync();

                ////}
                ////catch (Exception ex)
                ////{

                ////}
                //return productImageDto;
            }
            #endregion

            #region CrudAppService abp应用层封装了事务
            {
                //ProductImageDto productImageDto = new ProductImageDto();
                ////try
                ////{
                //ProductImage productImage = ObjectMapper.Map<ProductImageCreateDto, ProductImage>(input);
                //ProductImage productImage1 = await Repository.InsertAsync(productImage);
                //productImageDto = ObjectMapper.Map<ProductImage, ProductImageDto>(productImage1);
                ////
                //Order order = new Order();
                //order.OrderSn = "你好啊,8000";
                //order.TotalPrice = "8000";
                ////添加数据
                ////框架自动实现了事务
                //await orderRepository.InsertAsync(order);

                ////异常被捕获之后，框架事务会失效。
                ////throw new Exception("出现错误了");

                ////catch (Exception ex)
                ////{

                ////}
                //return productImageDto;
            }
            #endregion
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [Authorize("Product_Update")]
        //[Authorize("Product_Update_Custom_Test")]
        public override async Task<ProductImageDto> UpdateAsync(int id, ProductImageUpdateDto input)
        {
            //base.UpdateAsync();
            ProductImage productImage = await Repository.GetAsync(id);
            productImage.ProductImageOrders.ForEach(x => x.Descript = input.Url);
            //productImage.Url = input.Url;
            ProductImage productImage1 = await Repository.UpdateAsync(productImage);
            ProductImageDto productImageDto = ObjectMapper.Map<ProductImage, ProductImageDto>(productImage1);
            return productImageDto;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize("Product_Delete")]
        public override async Task DeleteAsync(int id)
        {
            await Repository.DeleteAsync(id);
        }
    }







    public interface ITestOrderAppService
    {
        Task<ProductImageDto> CreateAsync(ProductImageCreateDto input);
    }

    /// <summary>
    /// 测试事务
    /// </summary>
    [Dependency(ServiceLifetime.Transient)]
    public class TestOrderAppService : ITestOrderAppService
    {
        public TestOrderAppService()
        {

        }

        /// <summary>
        /// 属性
        /// </summary>
        public IProductImageRepository productImageRepository { get; set; }

        /// <summary>
        /// 属性注入
        /// </summary>
        //public IOrderRepository orderRepository { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public IObjectMapper ObjectMapper { get; set; }

        /// <summary>
        /// 测试事务 工作单元
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ProductImageDto> CreateAsync(ProductImageCreateDto input)
        {
            ProductImageDto productImageDto = new ProductImageDto();
            //try
            //{
            ProductImage productImage = ObjectMapper.Map<ProductImageCreateDto, ProductImage>(input);
            ProductImage productImage1 = await productImageRepository.InsertAsync(productImage);
            productImageDto = ObjectMapper.Map<ProductImage, ProductImageDto>(productImage1);
            //
            //Order order = new Order();
            //order.OrderSn = "你好啊,8000";
            //order.TotalPrice = "8000";

            ////添加数据
            ////框架自动实现了事务
            //await orderRepository.InsertAsync(order);

            //异常被捕获之后，框架事务会失效。
            //throw new Exception("出现错误了");

            //}
            //catch (Exception ex)
            //{

            //}
            return productImageDto;
        }
    }
}
